package com.example.demo.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StockService {

    /**
     * 模拟库存
     */
    private static Integer stock = 1000;

    @Autowired
    private OtherService otherService;

    /**
     * 减库存操作
     *
     * @return
     */
    public void subStock() {
        System.out.println(Thread.currentThread().getName() + " 进行减库存操作，当前剩余库存：" + this.getStock());
        stock--;
        if (stock.equals(100)) {
            //模拟发生异常
            throw new RuntimeException();
        }
    }

    /**
     * 并发安全的减库存操作
     */
    @RedisLock(key = "key")
    public void safeSubStock() {
        this.subStock();
        otherService.test();
    }

    public Integer getStock() {
        return stock;
    }

}
